package com.oa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.oa.mapper.NotifyMapper;
import com.oa.pojo.Notify;
import com.oa.pojo.User;
import com.oa.service.NotifyService;
import com.oa.utils.EntityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author Str
 * @Date 2021/12/16 16:11
 * @Description :
 */
@Service
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private NotifyMapper notifyMapper;

    @Override
    public Map<String, String> fileUpload(CommonsMultipartFile file) throws IOException, EntityException {
        Map<String, String> map = new HashMap<>();

        //获取文件名 : file.getOriginalFilename();
        String fileName = file.getOriginalFilename();

        // 获取文件大小
        long fileSize = file.getSize();

        //如果文件名为空，直接回到首页！
        if ("".equals(fileName)) {
            throw new EntityException("无法获取文件");
        }
        System.out.println("上传文件名 : " + fileName);

        //上传路径保存设置
//        String path = request.getServletContext().getRealPath("/upload");
        //如果路径不存在，创建一个
        File realPath = new File("D:\\Projects\\temp");
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, fileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();

        map.put("fileName", fileName);
        map.put("fileSize", fileSize + "");

        return map;
    }

    @Override
    public void addNotify(Map<String, String> map, String userId, String notifyName, String note) throws Exception {
        try {
            Notify notify = new Notify();
            //{3}设置 uuid 到 notify
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");

            notify.setId(uuid);
            notify.setNotifyName(notifyName);
            notify.setUploader(userId);
            notify.setFileName(map.get("fileName"));
            notify.setFileSize(map.get("fileSize"));
            notify.setDownTimes(0);
            notify.setNote(note);
            //{4}先写数据库(写不去会抛出异常)
            //   [同名异常(客户), sql格式(程序员)]
            notifyMapper.addNotify(notify);
        } catch (SQLException e) {
            throw new EntityException("新增公告失败");
        }
    }

    @Override
    public Page<Notify> getNotifyList(int page, int limit, Map data) {
        // 开启分页: true 获取记录数...
        Page<Notify> pages = PageHelper.startPage(page, limit, true);
        // PageHelper会拦截查找内容
        notifyMapper.queryList(data);
        return pages;
    }

    @Override
    public String fileDownloads(HttpServletRequest request, HttpServletResponse response, String notifyId) throws Exception {

        //要下载的图片地址
        String path = "D:\\Projects\\temp";
        String fileName = notifyMapper.getFileNameById(notifyId);

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path, fileName);
        //2、 读取文件--输入流
        InputStream input = new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //4、执行 写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

    @Override
    public String getFileNameById(String notifyId) {
        return notifyMapper.getFileNameById(notifyId);
    }

    @Override
    public int growDownloadCnt(String notifyId) {
        return notifyMapper.growDownloadCnt(notifyId);
    }

    @Override
    public Notify getNotify(String notifyId) {
        return notifyMapper.getNotifyById(notifyId);
    }

    @Override
    public void updateNotify(Notify notify) throws Exception {
        int update = notifyMapper.update(notify);
        if (update != 1) {
            throw new EntityException("修改失败");
        }
    }

    @Override
    public void delNotify(String notifyId) throws EntityException {
        int del = notifyMapper.delNotify(notifyId);
        if (del != 1) {
            throw new EntityException("删除失败");
        }
        System.out.println("delNotify:删除的条数:" + del);
//        // 获取文件地址
//        String path = "D:\\Projects\\temp";
//        String fileName = notifyMapper.getFileNameById(notifyId);
//        System.out.println("notifyId::"+notifyId);
//        System.out.println("fileName::"+fileName);
//        System.out.println("文件地址:" + path + fileName);
//        File file = new File(path, fileName);
//        if (!file.exists()) {
//            System.out.println(path + fileName + "文件不存在");
//        } else {
//            // 是一个文件同时文件存在
//            if (file.isFile()) {
//                if (file.delete()) {
//                    System.out.println(path + fileName + "文件删除成功");
//                } else System.out.println(path + fileName + "文件删除失败");
//            }
//        }
    }
}
